/**   
 * @Title: TrackingRecordDetailAct.java 
 * @Package: com.esun.rabbit2.viewer.mainact.mylotteryact.trackingrecord 
 * @Description: TODO(追号详情Activity) 
 * @Author: Billy qigs@500wan.com   
 * @Date: 2011-7-28 下午12:32:17  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.mylotteryact.trackingrecord;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.TrackingRecordDetailInfo;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.trackingrecord.CancleTrackingCommunicater;
import com.esun.rabbit2.communicaters.trackingrecord.TrackingRecordDetailCommunicater;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.LotteryRecordDetailAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.LotteryRecordDetailMoreAct;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: TrackingRecordDetailAct
 * @Description: TODO(追号详情Activity)
 * @Author: Billy qigs@500wan.com
 * @Date: 2011-7-28 下午12:32:17
 */
public class TrackingRecordDetailAct extends Activity implements OnClickListener {

	private TextView tvDate;
	private TextView tvUserName;
	private TextView tvAllMoney;
	private TextView tvFinishMoney;
	private TextView tvTotalNum;
	private TextView tvFinishNum;
	private TextView tvMainState;
	private TextView tvIsStop;

	private Button btnCancleAllTracking;
	private ImageButton btnBack;
	private ProgressDialog progressDialog;
	private Handler detailHandler;
	private Bundle bundle;
	private LinearLayout linearContent;
	private LinearLayout linearChild;
	private TrackingRecordDetailCommunicater detailCommunicater;
	private CancleTrackingCommunicater cancleCommunicater;

	private String lotID;
	private String pid;// 撤单用id
	private String serverMsg;
	private String mainID;
	private String mainState;
	private int clickedNum;
	private ArrayList<String> childState = new ArrayList<String>();

	private boolean isShow = true;
	private boolean isMainCancle = false;

	private static final int GET_DETAIL_SUCCEED = 1000001;
	private static final int GET_DETAIL_FAILED = 1000002;
	private static final int CANCLE_TRACKING_SUCCEED = 1000003;
	private static final int CANCLE_TRACKING_FAILED = 1000004;
	private static final String MAIN_TASK = "1";
	private static final String CHILD_TASK = "0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trackingrecorddetail_act);

		initUI();
		initHandler();
	}

	public void initUI() {

		progressDialog = ViewerUtil.showProgressDialog(TrackingRecordDetailAct.this, "正在加载,请稍后...");
		progressDialog.show();

		bundle = this.getIntent().getExtras();
		lotID = bundle.getString("lotid");
		pid = bundle.getString("pid");

		tvDate = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_addTime);
		tvUserName = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_userName);
		tvAllMoney = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_totalMoney);
		tvFinishMoney = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_finishMoney);
		tvTotalNum = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_totalNum);
		tvFinishNum = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_finishNum);
		tvMainState = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_mainState);
		tvIsStop = (TextView) findViewById(R.id.trackingrecorddetail_act_tv_isStop);

		linearContent = (LinearLayout) findViewById(R.id.trackingrecorddetail_act_linear_content);
		linearChild = (LinearLayout) findViewById(R.id.trackingrecorddetail_act_linear_childRecord);

		btnCancleAllTracking = (Button) findViewById(R.id.trackingrecorddetail_act_btn_cancleAllTracking);
		btnCancleAllTracking.setOnClickListener(this);

		btnBack = (ImageButton) findViewById(R.id.trackingrecorddetail_act_btn_back);
		btnBack.setOnClickListener(this);

		getTrackingRecordDetailThread();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.trackingrecorddetail_act_btn_back:

			TrackingRecordDetailAct.this.finish();

			break;

		case R.id.trackingrecorddetail_act_btn_cancleAllTracking:

			// 撤销所有追号
			isMainCancle = true;
			final Dialog tipDialog = new Dialog(TrackingRecordDetailAct.this, R.style.dialog);
			tipDialog.getWindow().setContentView(R.layout.dialog_quit);
			((TextView) tipDialog.getWindow().findViewById(R.id.dialogquit_tv_title)).setText("取消追号任务");
			((TextView) tipDialog.getWindow().findViewById(R.id.dialogquit_tv_msg)).setText("该操作将取消所有等待中的追号任务，确定要终止该任务吗？");
			((Button) tipDialog.getWindow().findViewById(R.id.dialogquit_btn_cancel)).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					tipDialog.cancel();
				}
			});
			((Button) tipDialog.getWindow().findViewById(R.id.dialogquit_btn_submit)).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					tipDialog.cancel();
					progressDialog.show();
					cancleTrackingThread(MAIN_TASK, mainID);
				}
			});
			tipDialog.show();

			break;

		default:
			break;
		}
	}

	// 撤销追号线程
	public void cancleTrackingThread(final String type, final String id) {
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				cancleCommunicater = new CancleTrackingCommunicater();
				Message msg = new Message();
				try {
					boolean isSucceed = cancleCommunicater.isCancleTracking(lotID, type, id);
					serverMsg = cancleCommunicater.getErrorMSG();
					if (isSucceed) {
						msg = detailHandler.obtainMessage(CANCLE_TRACKING_SUCCEED, null);
						detailHandler.sendMessage(msg);
					} else {
						msg = detailHandler.obtainMessage(CANCLE_TRACKING_FAILED, null);
						detailHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					// TODO: handle exception
					msg = detailHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					detailHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	// 获取详情线程
	public void getTrackingRecordDetailThread() {
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				detailCommunicater = new TrackingRecordDetailCommunicater();
				Message msg = new Message();
				try {
					boolean isSucceed = detailCommunicater.isGetTrackingRecordDetail(lotID, pid);
					serverMsg = detailCommunicater.getErrorMSG();
					if (isSucceed) {
						msg = detailHandler.obtainMessage(GET_DETAIL_SUCCEED, null);
						detailHandler.sendMessage(msg);
					} else {
						msg = detailHandler.obtainMessage(GET_DETAIL_FAILED, null);
						detailHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					// TODO: handle exception
					msg = detailHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					detailHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	public void initHandler() {
		detailHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);

				switch (msg.what) {
				case GET_DETAIL_SUCCEED:

					detailInfoDisplay();

					break;

				case GET_DETAIL_FAILED:

					showTipDialog(serverMsg);

					break;

				case CANCLE_TRACKING_SUCCEED:

					EDebug.o(this, "linear child has child count = " + linearChild.getChildCount());

					if (isMainCancle) {
						mainState = "2";
						EDebug.o(this, "main state = " + mainState);
						for (int i = 1; i < linearChild.getChildCount(); i++) {
							if (childState.get(i - 1).equals("0")) {
								EDebug.o(this, "i = " + i);
								((Button) linearChild.getChildAt(i - 1).findViewById(R.id.childtracking_each_line_btn_cancle)).setVisibility(View.GONE);
								((TextView) linearChild.getChildAt(i - 1).findViewById(R.id.childtracking_each_line_tv_state)).setText("已取消");
							}
						}
						showTipDialog("任务已终止");
						btnCancleAllTracking.setEnabled(false);
						btnCancleAllTracking.setVisibility(View.INVISIBLE);
						tvMainState.setText("被终止");
					} else {
						((Button) linearChild.getChildAt(clickedNum).findViewById(R.id.childtracking_each_line_btn_cancle)).setVisibility(View.GONE);
						((TextView) linearChild.getChildAt(clickedNum).findViewById(R.id.childtracking_each_line_tv_state)).setText("已取消");
						if (isAllCancle()) {
							mainState = "2";
							btnCancleAllTracking.setEnabled(false);
							btnCancleAllTracking.setVisibility(View.INVISIBLE);
							tvMainState.setText("被终止");
						}
						showTipDialog("撤单成功");
					}

					break;

				case CANCLE_TRACKING_FAILED:

					showTipDialog(serverMsg);

					break;

				case Config.CONNECTION_FAIL:

					showTipDialog(Language.STR_CONNECTIONFAIL);

					break;

				default:
					break;
				}
				if (progressDialog != null) {
					progressDialog.cancel();
				}
			}

		};
	}

	// 详情显示
	public void detailInfoDisplay() {
		TrackingRecordDetailInfo list = detailCommunicater.getDetailInfo();

		tvDate.setText(list.getAddTime());
		tvUserName.setText(list.getUserName());
		tvAllMoney.setText("￥" + moneyFormat(list.getAddMoney()));
		tvFinishMoney.setText("￥" + moneyFormat(list.getFinishMoney()));
		tvTotalNum.setText(list.getTotalNum() + "期");
		tvFinishNum.setText(list.getFinishNum() + "期");
		if (list.getIsStop().equals("0")) {
			tvIsStop.setText("否");
		} else {
			tvIsStop.setText("是");
		}
		mainState = list.getMainState();
		if (list.getMainState().equals("0")) {
			tvMainState.setText("进行中");
		} else if (list.getMainState().equals("1")) {
			tvMainState.setText("已完成");
			btnCancleAllTracking.setEnabled(false);
			btnCancleAllTracking.setVisibility(View.INVISIBLE);
		} else if (list.getMainState().equals("2")) {
			tvMainState.setText("被终止");
			btnCancleAllTracking.setEnabled(false);
			btnCancleAllTracking.setVisibility(View.INVISIBLE);
		}
		mainID = list.getMainID();

		programContentDisplay(list.getContent());
		trackingListJudgement(list.getExpect(), list.getOpenCode(), list.getChildID(), list.getChildState(), list.getGetMoney(), list.getPID());
		childState = list.getChildState();
	}

	// 方案内容显示处理
	public void programContentDisplay(String str) {
		if (str.equals("") || str.length() < 1) {
			View viewContent = TrackingRecordDetailAct.this.getLayoutInflater().inflate(R.layout.trackingrecord_content_each_line, null);
			TextView tvContentRed = (TextView) viewContent.findViewById(R.id.trackingcontent_each_line_tv_numRed);
			tvContentRed.setText("无方案");
			tvContentRed.setTextColor(this.getResources().getColor(R.color.solid_black));
			TextView tvContentBlue = (TextView) viewContent.findViewById(R.id.trackingcontent_each_line_tv_numBlue);
			tvContentBlue.setText("");

			linearContent.addView(viewContent);
			linearContent.setGravity(Gravity.CENTER);
		} else {
			final String[] eachContent = str.split("\\$");
			if (eachContent.length <= 7) {
				for (int i = 0; i < eachContent.length; i++) {
					String[] colorDivide = eachContent[i].split("\\|");
					EDebug.o(this, colorDivide[0] + "====" + colorDivide[1]);
					View viewContent = TrackingRecordDetailAct.this.getLayoutInflater().inflate(R.layout.trackingrecord_content_each_line, null);
					TextView tvContentRed = (TextView) viewContent.findViewById(R.id.trackingcontent_each_line_tv_numRed);
					tvContentRed.setText(colorDivide[0].replace(',', ' '));
					TextView tvContentBlue = (TextView) viewContent.findViewById(R.id.trackingcontent_each_line_tv_numBlue);
					tvContentBlue.setText(colorDivide[1].replace(',', ' '));
					linearContent.addView(viewContent);
				}
			} else {
				for (int i = 0; i < 7; i++) {
					String[] colorDivide = eachContent[i].split("\\|");
					View viewContent = TrackingRecordDetailAct.this.getLayoutInflater().inflate(R.layout.trackingrecord_content_each_line, null);
					TextView tvContentRed = (TextView) viewContent.findViewById(R.id.trackingcontent_each_line_tv_numRed);
					tvContentRed.setText(colorDivide[0].replace(',', ' '));
					TextView tvContentBlue = (TextView) viewContent.findViewById(R.id.trackingcontent_each_line_tv_numBlue);
					tvContentBlue.setText(colorDivide[1].replace(',', ' '));
					linearContent.addView(viewContent);
				}
				Button btnMore = new Button(TrackingRecordDetailAct.this);
				btnMore.setText("...");
				btnMore.setBackgroundResource(R.drawable.lotteryrecord_detail_btn_more);
				btnMore.setTextColor(getResources().getColor(R.color.solid_black));
				btnMore.setWidth(LayoutParams.FILL_PARENT);
				btnMore.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 跳到另一页面显示全部方案内容
						startActivity(new Intent(TrackingRecordDetailAct.this, LotteryRecordDetailMoreAct.class).putExtra("classify", "txt").putExtra("content", eachContent).putExtra(Key.KEY_LOTID, lotID));
					}
				});
				linearContent.addView(btnMore);
			}
		}
	}

	// 每期追号记录判断
	public void trackingListJudgement(final ArrayList<String> exp, final ArrayList<String> code, final ArrayList<String> id, final ArrayList<String> state, final ArrayList<String> getMoney,
			final ArrayList<String> cpid) {
		if (exp.size() <= 7) {
			// 直接显示
			EDebug.o(this, "总体子追号小于7");
			trackingListDisplay(exp, code, id, state, getMoney, 0, exp.size(), cpid);
		} else {
			EDebug.o(this, "总体子追号大于7");
			if (detailCommunicater.getDetailInfo().getMainState().equals("1") || detailCommunicater.getDetailInfo().getMainState().equals("2")) {
				// 显示0~7
				EDebug.o(this, "已完成或已终止显示前七个");
				trackingListDisplay(exp, code, id, state, getMoney, 0, 7, cpid);
			} else {
				int currentExcept = 0;
				for (int i = 0; i < exp.size(); i++) {
					if (state.get(i).equals("1")) {
						currentExcept = i;
						break;
					}
				}
				if (currentExcept <= 2) {
					// 显示0~7
					EDebug.o(this, currentExcept + "<=2" + "显示前七个");
					trackingListDisplay(exp, code, id, state, getMoney, 0, 7, cpid);
				} else if (exp.size() - currentExcept <= 5) {
					// 显示后7个
					EDebug.o(this, "显示后七个");
					trackingListDisplay(exp, code, id, state, getMoney, exp.size() - 7, exp.size() - 1, cpid);
				} else {
					// 显示中间7个
					EDebug.o(this, "显示中间七个");
					trackingListDisplay(exp, code, id, state, getMoney, currentExcept - 2, currentExcept + 4, cpid);
				}
			}
			Button btnMoreChild = new Button(TrackingRecordDetailAct.this);
			btnMoreChild.setText("...");
			btnMoreChild.setBackgroundResource(R.drawable.lotteryrecord_detail_btn_more);
			btnMoreChild.setTextColor(getResources().getColor(R.color.solid_black));
			btnMoreChild.setWidth(LayoutParams.FILL_PARENT);
			btnMoreChild.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Bundle bundle = new Bundle();
					bundle.putString(Key.KEY_LOTID, lotID);
					bundle.putStringArrayList(Key.KEY_EXP, exp);
					bundle.putStringArrayList(Key.KEY_CODE, code);
					bundle.putStringArrayList(Key.KEY_ID, id);
					bundle.putStringArrayList(Key.KEY_STATE, state);
					bundle.putStringArrayList(Key.KEY_GETMONEY, getMoney);
					bundle.putStringArrayList(Key.KEY_CPID, cpid);
					bundle.putString(Key.KEY_MAINID, mainID);
					bundle.putString(Key.KEY_MAINSTATE, mainState);
					startActivity(new Intent(TrackingRecordDetailAct.this, TrackingRecordDetailMoreAct.class).putExtras(bundle));
				}
			});
			linearChild.addView(btnMoreChild);
		}
	}

	// 每期追号记录显示
	public void trackingListDisplay(final ArrayList<String> exp, ArrayList<String> code, final ArrayList<String> id, ArrayList<String> state, ArrayList<String> getMoney, int start, int end,
			final ArrayList<String> cpid) {

		for (int i = start; i < end; i++) {
			final String winMoney;
			final int _i = i;
			View viewChild = TrackingRecordDetailAct.this.getLayoutInflater().inflate(R.layout.trackingrecord_child_each_line, null);
			viewChild.setTag(i);
			TextView tvExpect = (TextView) viewChild.findViewById(R.id.childtracking_each_line_tv_expect);
			tvExpect.setText(exp.get(i));
			TextView tvChildRed = (TextView) viewChild.findViewById(R.id.childtracking_each_line_tv_numRed);
			TextView tvChildBlue = (TextView) viewChild.findViewById(R.id.childtracking_each_line_tv_numBlue);
			if (!code.get(i).equals("")) {
				String[] strCode = code.get(i).split("\\|");
				tvChildRed.setText(strCode[0].replace(',', ' '));
				tvChildBlue.setText(strCode[1].replace(',', ' '));
			} else {
				tvChildRed.setText(Config.NULLMARK);
				tvChildBlue.setText("未开奖");
				tvChildBlue.setTextColor(getResources().getColor(R.color.solid_black));
			}
			TextView tvState = (TextView) viewChild.findViewById(R.id.childtracking_each_line_tv_state);
			tvState.setTag("state");
			Button btnChild = (Button) viewChild.findViewById(R.id.childtracking_each_line_btn_cancle);
			EDebug.o(this, id.get(i));
			btnChild.setTag("btn");
			btnChild.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					final Dialog tipDialog = new Dialog(TrackingRecordDetailAct.this, R.style.dialog);
					tipDialog.getWindow().setContentView(R.layout.dialog_quit);
					((TextView) tipDialog.getWindow().findViewById(R.id.dialogquit_tv_title)).setText("取消追号任务");
					((TextView) tipDialog.getWindow().findViewById(R.id.dialogquit_tv_msg)).setText("您要取消第" + exp.get(_i) + "期任务吗？");
					((Button) tipDialog.getWindow().findViewById(R.id.dialogquit_btn_cancel)).setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							tipDialog.cancel();
						}
					});
					((Button) tipDialog.getWindow().findViewById(R.id.dialogquit_btn_submit)).setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							isMainCancle = false;
							tipDialog.cancel();
							progressDialog.show();
							clickedNum = _i + 1;
							cancleTrackingThread(CHILD_TASK, id.get(_i));
							EDebug.o(this, id.get(_i));
						}
					});
					tipDialog.show();
				}
			});
			ImageView arrow = (ImageView) viewChild.findViewById(R.id.trackingrecord_child_each_line_iv_arrow);

			if (state.get(i).equals("0")) {
				winMoney = "";
				btnChild.setVisibility(View.VISIBLE);
				arrow.setVisibility(View.INVISIBLE);
				viewChild.setClickable(false);
				viewChild.setEnabled(false);
			} else if (state.get(i).equals("4")) {
				winMoney = moneyFormat(getMoney.get(i));
				tvState.setText("￥" + moneyFormat(getMoney.get(i)));
				tvState.setTextColor(getResources().getColor(R.color.kjxx_red));
			} else {
				winMoney = "";
				tvState.setText(childStateTransfer(state.get(i)));
				if (state.get(i).equals("2")) {
					arrow.setVisibility(View.INVISIBLE);
					viewChild.setClickable(false);
					viewChild.setEnabled(false);
				}
			}
			// 点击进入购彩详情
			viewChild.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					EDebug.o(this, _i);
					startActivity(new Intent(TrackingRecordDetailAct.this, LotteryRecordDetailAct.class).putExtra("lotid", lotID).putExtra("id", cpid.get(_i)).putExtra("winMoney", winMoney));
				}
			});

			linearChild.addView(viewChild);
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
		isShow = false;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
		isShow = true;
		if (UserInfo.getUserInfo().isRebuy()) {
			this.finish();
		}
	}

	public void showTipDialog(String str) {
		if (isShow) {
			ViewerUtil.showTipDialog(TrackingRecordDetailAct.this, str, false);
		}
	}

	public String childStateTransfer(String str) {
		String childState = null;
		switch (Integer.valueOf(str)) {
		case 0:
			childState = "等待中";
			break;
		case 1:
			childState = "未开奖";
			break;
		case 2:
			childState = "已取消";
			break;
		case 3:
			childState = "未中奖";
			break;
		case 4:
			childState = "中奖";
			break;
		default:
			break;
		}

		return childState;
	}

	// 控制金钱显示位数（待整理）
	public String moneyFormat(String str) {
		double userRestTemp = Double.parseDouble(str);
		DecimalFormat format = new DecimalFormat("0.00");
		String afterBet = format.format(userRestTemp);
		return afterBet;
	}

	// 判断是否全部取消追号
	public boolean isAllCancle() {
		boolean isAllCancle = true;
		for (int i = 1; i < linearChild.getChildCount(); i++) {
			if (((Button) linearChild.getChildAt(i).findViewById(R.id.childtracking_each_line_btn_cancle)).getVisibility() == View.VISIBLE) {
				isAllCancle = false;
				break;
			}
		}
		return isAllCancle;
	}

}
